//
//  ChoseAddressViewController.m
//  PeopleStreet
//
//  Created by 辰领科技 on 16/1/15.
//  Copyright © 2016年 yuf. All rights reserved.
//

#import "ChoseAddressViewController.h"
#import "ChoseAddressTableViewCell.h"
#import "AddAddressViewController.h"
static NSString *cellIdentify = @"ChoseAddressTableViewCell";
@interface ChoseAddressViewController ()<UITableViewDataSource,UITableViewDelegate>{
    NSInteger _totle;
}
@property (nonatomic,assign)   NSInteger    pageNO;
@property (strong, nonatomic) IBOutlet UIView *navView;
@property (strong, nonatomic) IBOutlet UITableView *tabview;
@property(nonatomic,strong)NSMutableArray * addressArray;

@end



@implementation ChoseAddressViewController

- (void)viewWillAppear:(BOOL)animated{

    [self addRefreshing];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    _pageNO =  1;
    _addressArray = [NSMutableArray array];
    _totle = 0;
    [self initViewLayout];
    [self addRefreshing];
    // Do any additional setup after loading the view.
}
#pragma mark  布局调整--=========================================
- (void)initViewLayout{
    //功能栏
    [self adaptiveViewLayout:self.view];
    [self adaptiveViewLayout:self.navView];
    [self adaptiveViewLayout:self.tabview];
    
    //注册
    [self.tabview registerClass:[ChoseAddressTableViewCell class]  forCellReuseIdentifier:cellIdentify];
   
    self.tabview.separatorStyle = NO;
}


#pragma mark -- 添加刷新数据
- (void)addRefreshing{
    self.tabview.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        int64_t delayInSeconds = 8.0;
        dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
        dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
            [self.tabview.header endRefreshing];
        });
        self.pageNO = 1;
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            //请求商家数据
            [self getAddressList];
        });
    }];
    // 马上进入刷新状态
    [self.tabview.header beginRefreshing];
}
//加载更多数据
- (void)loadMoreData{
    if (self.addressArray.count == _totle) {
        [self.tabview.footer endRefreshing];
    }else{
        self.pageNO = self.pageNO + 1;
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            //请求商家数据
            [self getAddressList];
        });
    }
    
}



- (void)getAddressList{
    NSMutableDictionary  *dic=[NSMutableDictionary dictionary];
    NSDictionary * dic1 =  [Common getLoginInfo];
    [dic setObject:dic1[@"userId"] forKey:@"msadMemberId"];
    self.shareApi.delegate=self;
    [self.shareApi  requestOperationWithDic:dic withPath:SX_GetAddressList withHttpType:@"POST" withTag:SX_SX_AddressList];

}

- (IBAction)back:(id)sender {
    [self.navigationController  popViewControllerAnimated:YES];
}

- (IBAction)addAddress:(id)sender {
    UIStoryboard *secondStroyBoard=[UIStoryboard storyboardWithName:@"HomeStoryboard" bundle:nil];
    AddAddressViewController *page = [secondStroyBoard instantiateViewControllerWithIdentifier:@"AddAddress"];
    page.addressDic = @{};
    [self.navigationController   pushViewController:page animated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


#pragma mark -- UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    ChoseAddressTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentify forIndexPath:indexPath];
    if (!cell) {
        cell = [[ChoseAddressTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentify];
    }
    cell.selectionStyle=UITableViewCellSelectionStyleNone;
    
    for (UIView *view in cell.subviews) {
        if ([view isKindOfClass:[UILabel class]] ||[view isKindOfClass:[UIImageView class]]||[view isKindOfClass:[UIScrollView class]]||[view isKindOfClass:[UIButton class]]) {
            [view removeFromSuperview];
        }
    }

    cell.reciverName.text = _addressArray[indexPath.row][@"msadReceiverName"];
    cell.reciverPhone.text = _addressArray[indexPath.row][@"msadMobileNo"];
    cell.reciverAddress.frame = flexibleFrame(CGRectMake(90, 67, 190, 0), YES);
    cell.reciverAddress.numberOfLines = 0;
    cell.reciverAddress.text = _addressArray[indexPath.row][@"msadAddr"];
    [cell.reciverAddress sizeToFit];
    
    
    
    cell.editingBlock = ^(NSString *str){
        if ([str isEqualToString:@"1"]) {
            UIStoryboard *secondStroyBoard=[UIStoryboard storyboardWithName:@"HomeStoryboard" bundle:nil];
            AddAddressViewController *page = [secondStroyBoard instantiateViewControllerWithIdentifier:@"AddAddress"];
            page.addressDic = _addressArray[indexPath.row];
            [self.navigationController   pushViewController:page animated:YES];

        }
        };
    
    return cell;
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
    {
        return _addressArray.count;
    }
    
    
    
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
    {
        return 130*VerticalRatio();
    }

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    _addressBlock(_addressArray[indexPath.row]);
    [self.navigationController  popViewControllerAnimated:YES];
}

#pragma   mark---- GetADBanner Request Delegate

-(void)fetchDatabaseFinished:(NSMutableDictionary *)database withTag:(NSInteger)tag{
    [_tabview.header endRefreshing];
    [_tabview.footer endRefreshing];
    if (tag==SX_SX_AddressList) {
        
        if (  [[database valueForKey:@"type"] integerValue]!=1 ) {
            
            [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
            
        }else  {
            dispatch_async(dispatch_get_main_queue(), ^{
//                _totle = [database[@"result"][@"totalResults"] integerValue];
//                _totle = [database[@"result"] integerValue];
                if (_totle > PageSize) {
                    __weak __typeof(self) weakSelf = self;
                    if (!self.tabview.footer) {
                        // 设置回调（一旦进入刷新状态就会调用这个refreshingBlock）
                        self.tabview.footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
                            [weakSelf loadMoreData];
                        }];
                    }
                }
                if (self.pageNO == 1) {
                    [self.addressArray removeAllObjects];
                }
//                NSArray *arr = database[@"result"][@"pageRecord"];
                NSArray *arr = database[@"result"];
                for (id entity in arr) {
                    [self.addressArray addObject:entity];
                }
                _tabview.dataSource = self;
                _tabview.delegate = self;
                [_tabview reloadData];
                
            });
            
            
            
        }

        }
        
}

-(void)fetchDatabaseFailed:(NSError *)error message:(NSString *)message{
    
    //
    [self dismissWaitDialog];
    
    
}


@end
